package com.itheima.config;

import cn.hutool.jwt.Claims;
import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.JwtUtils;
import com.itheima.common.R;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * @author
 * @ClassName WebHandlerIntercept
 * @Description JWT的拦截器
 * @date 2022/6/9 23:53
 */
@Component
public class JwtHandlerIntercept implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(JwtHandlerIntercept.class);
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        //如果传入的token为空值，则拦截
        if (StringUtils.isEmpty(token)) {
            //将result对象转换为json字符串
            String str = objectMapper.writeValueAsString(R.error("暂未登录，请您先登录！"));
            //设置相应数据类型为application/json并设置编码为utf-8
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(str);
            return false;
        }
        //判断是否过期
        Claims claims = (Claims) JwtUtils.checkJwt(token);
        if (claims == null) {
            response.setContentType("application/json;charset=utf-8");
            String str = objectMapper.writeValueAsString(R.error("暂未登录，请您先登录！"));
            response.getWriter().write(str);
            return false;
        }
        return true;
    }
}